<?php
//Needed for connectDB()
require("dbFunctions.php");

/**
 * Adds a new Requestor to the database.
 * This file should be hidden from users using the web interface and is used to populate the database
 * from the mobile device specifically.
 *
 * Author: Steve Gennaoui
 * Date: 10/30/2012
 */

//Get the parameters
$first_name = $_REQUEST['fname'];
$last_name = $_REQUEST['lname'];
$email = $_REQUEST['email'];

//Verify that firstname, lastname, and email are non-null.
// If the email is not a valid email, filter_var returns false.
if( is_null($first_name) )
	die("No first name provided.");
if( is_null($last_name) )
	die("No last name provided.");
if( !filter_var($email,FILTER_VALIDATE_EMAIL) )
	die("Email is not in a valid format.");

//Force emails to be lowercase
$email = strtolower($email);
//Get a PDO Database connection
$dbh = connectDB();

//Construct the query to add a new Requestor
// Leave the is_active field alone so that the default value of True is used.
$query =  "INSERT INTO Requestors (first_name, last_name, email) VALUES (:first_name, :last_name, :email)";

if(getIDByEmail($email, "Requestors") > 0)
	die("$email has already beed added.");

//Check to see if this email has already been entered and is merely deactivated.
// If so, then just re-activate the Requestor.
$req_id = getIDByEmail($email,"Requestors",1);
if( $req_id > 0 )
{
    $query = "UPDATE Requestors SET is_active=true WHERE req_id=:req_id";
    $stmt = $dbh->prepare($query);
    $stmt->bindParam(':req_id',$req_id);
    $stmt->execute();
    exit("Reactivated requestor with email: $email");
}

//Create a PDO Statement by preparing the query
$stmt = $dbh->prepare( $query );

//Bind parameters to avoid SQL injection
$stmt->bindParam(':first_name', $first_name);
$stmt->bindParam(':last_name', $last_name);
$stmt->bindParam(':email', $email);

//Execute the PDO Statement
$stmt->execute();

//Release the PDO Statement and PDO database connection
$stmt = null;
$dbh = null;

?>
